package cn.gok.springsecuritydemo01.authenticationHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
    自定义登录失败的处理器
 */
public class LoginFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf8");
        Map<String, Object> map = new HashMap<>();
        map.put("code","0");
        map.put("msg","登录失败");

        String jsonString = new ObjectMapper().writeValueAsString(map);
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
    }
}
